<template>
  <div class="activities-container">
    <h2>活动管理</h2>
    
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="活动标题">
          <el-input v-model="searchForm.titleFuzzy" placeholder="请输入活动标题" clearable />
        </el-form-item>
        <el-form-item label="社团">
          <el-select v-model="searchForm.clubId" placeholder="请选择社团" clearable style="width: 200px;">
            <el-option
              v-for="club in clubList"
              :key="club.id"
              :label="club.name"
              :value="club.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增活动</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 活动列表 -->
    <el-table :data="activityList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="活动标题" />
      <el-table-column prop="clubName" label="所属社团" />
      <el-table-column prop="location" label="活动地点" />
      <el-table-column prop="startTime" label="开始时间" :formatter="formatDateTime" />
      <el-table-column prop="endTime" label="结束时间" :formatter="formatDateTime" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            v-if="scope.row.status === 1" 
            type="warning" 
            size="small" 
            @click="handleToggleStatus(scope.row)"
          >
            禁用
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 活动表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="activityForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="activityForm.title" />
        </el-form-item>
        <el-form-item label="所属社团" prop="clubId">
          <el-select v-model="activityForm.clubId" placeholder="请选择社团">
            <el-option
              v-for="club in clubList"
              :key="club.id"
              :label="club.name"
              :value="club.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="activityForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input type="textarea" v-model="activityForm.description" rows="3" />
        </el-form-item>
        <el-form-item label="活动图片" prop="image">
          <el-input v-model="activityForm.image" placeholder="请输入图片地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 列表数据
const activityList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const clubList = ref([])

// 搜索表单
const searchForm = reactive({
  titleFuzzy: '',
  clubId: '',
  timeRange: []
})

// 活动表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const activityForm = reactive({
  id: '',
  title: '',
  clubId: '',
  timeRange: [],
  location: '',
  description: '',
  image: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  clubId: [{ required: true, message: '请选择所属社团', trigger: 'change' }],
  timeRange: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }]
}

// 加载活动列表
const loadActivities = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      titleFuzzy: searchForm.titleFuzzy,
      clubId: searchForm.clubId
    }
    
    if (searchForm.timeRange?.length === 2) {
      params.startTimeStart = searchForm.timeRange[0]
      params.endTimeEnd = searchForm.timeRange[1]
    }

    const res = await axios.get('/activity/loadDataList', { params })
    if (res.data.status === 'success') {
      activityList.value = res.data.data.list
      total.value = res.data.data.totalCount
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 加载社团列表
const loadClubs = async () => {
  try {
    const res = await axios.get('/club/admin/loadDataList') // 修改请求路径
    if (res.data.status === 'success') {
      clubList.value = res.data.data.list
    }
  } catch (error) {
    console.error('获取社团列表失败:', error)
  }
}

const getStatusType = (status) => {
  const types = {
    '已禁用': 'info',
    '进行中': 'success',
    '已结束': 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    '已禁用': '已禁用',
    '进行中': '进行中',
    '已结束': '已结束'
  }
  return texts[status] || '未知'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadActivities()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  loadActivities()
}

// 新增活动
const handleAdd = () => {
  dialogTitle.value = '新增活动'
  dialogVisible.value = true
  Object.keys(activityForm).forEach(key => {
    activityForm[key] = ''
  })
  activityForm.timeRange = []
}

// 编辑活动
const handleEdit = (row) => {
  dialogTitle.value = '编辑活动'
  dialogVisible.value = true
  Object.keys(activityForm).forEach(key => {
    if (key === 'timeRange') {
      activityForm.timeRange = [row.startTime, row.endTime]
    } else {
      activityForm[key] = row[key]
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...activityForm,
          startTime: dayjs(activityForm.timeRange[0]).format('YYYY-MM-DD HH:mm:ss'), // 格式化开始时间
          endTime: dayjs(activityForm.timeRange[1]).format('YYYY-MM-DD HH:mm:ss') // 格式化结束时间
        }
        delete data.timeRange

        const url = data.id ? '/activity/updateActivityById' : '/activity/add'
        const res = await axios.post(url, data)
        if (res.data.status === 'success') {
          ElMessage.success(data.id ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadActivities()
        }
      } catch (error) {
        console.error(activityForm.id ? '更新活动失败:' : '添加活动失败:', error)
        ElMessage.error(activityForm.id ? '更新失败' : '添加失败')
      }
    }
  })
}

// 切换活动状态
const handleToggleStatus = async (row) => {
  if (row.status === 1) { // 只允许禁用状态为1的活动
    try {
      await ElMessageBox.confirm(
        '确定要禁用该活动吗？', 
        '提示',
        { type: 'warning' }
      )
      const res = await axios.post('/admin/activity/toggleStatus', {
        id: row.id,
        status: 0 // 设置为禁用状态
      })
      if (res.data.status === 'success') {
        ElMessage.success('禁用成功')
        loadActivities()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  }
}

// 删除活动
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该活动吗？', '提示', {
      type: 'warning'
    })
    const res = await axios.post('/activity/deleteActivityById', {
      id: row.id
    })
    if (res.data.status === 'success') {
      ElMessage.success('删除成功')
      loadActivities()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 清理 ResizeObserver
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
    resizeObserver.value = null
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadActivities()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadActivities()
}

// 格式化时间
const formatDateTime = (row, column) => {
  return row[column.property] ? dayjs(row[column.property]).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 添加 ResizeObserver 实例
const resizeObserver = ref(null)

onMounted(() => {
  loadActivities()
  loadClubs()

  // 示例：假设有一个元素需要观察
  const element = document.querySelector('.some-element-to-observe')
  if (element) {
    resizeObserver.value = new ResizeObserver(entries => {
      for (let entry of entries) {
        console.log('Element size changed:', entry.contentRect)
      }
    })
    resizeObserver.value.observe(element)
  }
})

// 添加卸载时的清理逻辑
onUnmounted(() => {
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
  }
})

</script>

<style scoped>
.activities-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  z-index: 1;
  position: relative;
}

:deep(.el-pagination) {
  margin: 0;
  padding: 0;
}
</style>